package com.action.ui.fragment;


import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.action.childbase.ChildBaseFragment;
import com.action.entity.RedPacketCommentEvent;
import com.action.entity.Redpacket;
import com.action.entity.XyBUserRecvRed;
import com.action.entity.event.RedPacketChangeEvent;
import com.action.service.pressenter.MemberPressenter;
import com.action.ui.activity.OpenPacketActivity;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.app_core.View.xrecyclerview.RecyclerAdapter;
import com.base.app_core.View.xrecyclerview.RecyclerViewHolder;
import com.base.app_core.model.MoneyData;
import com.base.app_core.model.Paginated;
import com.base.app_core.service.user.model.HomeRxBean;
import com.base.app_core.util.AppConstants;
import com.base.app_core.util.XYBAUtils;
import com.blankj.utilcode.util.StringUtils;
import com.xinglai.yun.R;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.thread.EventThread;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 */
public class SendHistoryRedPacketFrag extends ChildBaseFragment<MemberPressenter> {

    @BindView(R.id.snd_money)
    TextView msndMoney;

    @BindView(R.id.data_container)
    XRecyclerView dataContainer;

    @Inject
    MoneyData moneyData;

    private RedSndAdapter redSndAdapter;
    private Boolean hasMore = true;

    public SendHistoryRedPacketFrag() {
    }

    private int pageNo = 1;


    @Override
    protected boolean needShowError() {
        return true;
    }

    @Subscribe(thread = EventThread.MAIN_THREAD)
    public void consumeRedPacketCommentEvent(RedPacketCommentEvent commentEvent) {
        if (commentEvent == null) {
            return;
        }

        long redpacketId = commentEvent.getRedpacketId();
        Redpacket redpacket = new Redpacket();
        redpacket.setId(redpacketId);
        List<XyBUserRecvRed> list = redSndAdapter.getList();
        if (XYBAUtils.isEmpty(list)) {
            return;
        }

        if (list.contains(redpacket)) {
            int i = list.indexOf(redpacket);
            XyBUserRecvRed xyBUserRecvRed = list.get(i);
            xyBUserRecvRed.setCommentCount(commentEvent.getCommontCount());
            list.set(i, xyBUserRecvRed);
            redSndAdapter.notifyDataSetChanged();
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD)
    public void consumeRedPacketRobEvent(HomeRxBean homeRxBean) {
        if (homeRxBean.getStatus() == HomeRxBean.SEND_REDPACKET) {
            RedPacketChangeEvent redPacketChangeEvent = (RedPacketChangeEvent) homeRxBean.getBean();
            if (redPacketChangeEvent.getStatus() == RedPacketChangeEvent.PACKET_ROBED) {

                Redpacket redpacket = redPacketChangeEvent.getRedpacket();
                if (redpacket == null) {
                    return;
                }

                List<XyBUserRecvRed> list = redSndAdapter.getList();
                if (XYBAUtils.isEmpty(list)) {
                    return;
                }

                if (list.contains(redpacket)) {
                    int i = list.indexOf(redpacket);
                    XyBUserRecvRed xyBUserRecvRed = list.get(i);
                    xyBUserRecvRed.setSelfRob(true);
                    list.set(i, xyBUserRecvRed);
                    redSndAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    protected void loadData() {
        super.loadData();
        if (null != mPresenter)
            mPresenter.fetchSendHistoryRedPackets(pageNo);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(this);
    }

    @Override
    protected void setupComponent() {
        super.setupComponent();
        getChildViewComponent().inject(this);
    }

    public class RedSndAdapter extends RecyclerAdapter<XyBUserRecvRed, RedSndAdapter.ViewHolder> {


        @Override
        protected void fillData(final XyBUserRecvRed item, final ViewHolder holder) {
            XYBAUtils.displayCircleImage(holder.itemView.getContext(), item.getWxIcon(), holder.userImage);
            holder.senderContenet.setText(item.getContent());
            holder.senderTime.setText(item.getCreatedAt());
            holder.commentCount.setText("评：" + item.getCommentCount());
            holder.readCount.setText("阅：" + item.getViewCount());
            holder.imgContainer.removeAllViews();
            if (item.isSelfRob()) {
                holder.isSelfRob.setVisibility(View.GONE);
            } else {
                holder.isSelfRob.setVisibility(View.VISIBLE);
            }
            if (!StringUtils.isEmpty(item.getImgs())) {
                final String[] images = item.getImgs().split(",");
                if (null != images && images.length != 0) {
                    int index = 0;
                    for (String strimage : images) {
                        if (index >= 3)
                            break;
                        View view = LayoutInflater.from(holder.itemView.getContext()).inflate(R.layout.unit_image_layout, null);
                        ImageView imageView = view.findViewById(R.id.image_view);
                        XYBAUtils.displayImage(holder.itemView.getContext(), strimage, imageView, XYBAUtils.dip2px(80), XYBAUtils.dip2px(80));
                        holder.imgContainer.addView(view);
                        index++;
                    }
                }
            }

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ARouter.getInstance().build("/redpacket/detail").withString("sn", item.getSn())
                            .withInt("type", item.getType()).withBoolean("fromOpen", false).navigation();
                }
            });

            holder.isSelfRob.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (item == null) {
                        return;
                    }

                    if (item.isSelfRob()) {
                        int type = item.getType();
//                        if (type == 2) {
                            ARouter.getInstance().build(AppConstants.ROUTEURI.BASE_AD_VIEW).withString("sn", item.getSn())
                                    .withBoolean("fromOpen", false).navigation();
//                        } else {
//                            ARouter.getInstance().build("/redpacket/detail").withString("sn", item.getSn())
//                                    .withInt("type", type).withBoolean("fromOpen", false).navigation();
//                        }
                    } else {
                        startActivity(new Intent(getActivity(), OpenPacketActivity.class)
                                .putExtra(RedMapFrament.OPEN_PACKAGE, item));
                    }
                }
            });
        }

        @Override
        protected int getItemLayoutId() {
            return R.layout.unit_user_snd_redpacket;
        }

        public class ViewHolder extends RecyclerViewHolder {
            @BindView(R.id.user_image)
            ImageView userImage;
            @BindView(R.id.sender_contenet)
            TextView senderContenet;
            @BindView(R.id.img_container)
            LinearLayout imgContainer;
            @BindView(R.id.sender_time)
            TextView senderTime;
            @BindView(R.id.comment_count)
            TextView commentCount;
            @BindView(R.id.read_count)
            TextView readCount;
            @BindView(R.id.isSelfRob)
            ImageView isSelfRob;

            public ViewHolder(View itemView) {
                super(itemView);
            }

        }
    }

    @Override
    protected void initView() {
        super.initView();
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        dataContainer.setLayoutManager(layoutManager);
        redSndAdapter = new RedSndAdapter();
        dataContainer.setAdapter(redSndAdapter);
        dataContainer.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                if (dataContainer == null) {
                    return;
                }
                pageNo = 1;
                if (null != mPresenter)
                    mPresenter.fetchSendHistoryRedPackets(pageNo);
                dataContainer.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (getActivity() != null && null != dataContainer && !getActivity().isFinishing() && !getActivity().isDestroyed())
                            dataContainer.refreshComplete();
                    }
                }, AppConstants.Const.REFRESHTIME);
            }

            @Override
            public void onLoadMore() {
                if (!hasMore) {
                    return;
                }

                if (dataContainer == null) {
                    return;
                }
                pageNo++;
                if (null != mPresenter)
                    mPresenter.fetchSendHistoryRedPackets(pageNo);
                dataContainer.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (getActivity() != null && null != dataContainer && !getActivity().isFinishing() && !getActivity().isDestroyed())
                            dataContainer.loadMoreComplete();
                    }
                }, AppConstants.Const.REFRESHTIME);
            }
        });

        RxBus.get().register(this);
    }

    @Override
    public <T> void notifyData(T object, Class tClass, Paginated paginated) {
        super.notifyData(object, tClass, paginated);
        if (object instanceof Collection) {
            if (tClass == XyBUserRecvRed.class) {
                if (redSndAdapter == null || dataContainer == null) {
                    return;
                }

                if (pageNo == 1) {
                    redSndAdapter.clear();
                }
                redSndAdapter.addAll((List<XyBUserRecvRed>) object);
                redSndAdapter.notifyDataSetChanged();
                if (dataContainer != null) {
                    hasMore = paginated.getHasMore();
                    dataContainer.setLoadingMoreEnabled(hasMore);
                }
                setState(AppConstants.STATE_SUCCESS);
            }
        } else if (object == null && paginated.getCount() == 0) {
            setState(AppConstants.STATE_SUCCESS);
        }

        if (!StringUtils.isEmpty(moneyData.getSndMoney()) && msndMoney != null) {
            msndMoney.setText(new BigDecimal(moneyData.getSndMoney()).setScale(4, RoundingMode.DOWN).toPlainString());
        }
    }

    @Override
    protected boolean isNeedShowLoading() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_send_history_red_packet;
    }


}
